import { Directive, ElementRef, Renderer2, Inject, Output, EventEmitter, Input, OnChanges, SimpleChanges } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Directive({
  selector: '[appClickOutside]'
})
export class ClickOutsideDirective implements OnChanges {
  @Input()
  bindClick = false;

  @Output('appClickOutside')
  onClickOutside: EventEmitter<void> = new EventEmitter<void>();

  private handleClick: () => void = () => { };

  constructor(
    private el: ElementRef,
    private renderer: Renderer2,
    @Inject(DOCUMENT) private doc: Document
  ) { }

  ngOnChanges(changes: SimpleChanges): void {
    const bindClickChange = changes['bindClick'];
    if (bindClickChange && !bindClickChange.firstChange) {
      if (this.bindClick) {
        this.handleClick = this.renderer.listen(this.doc, 'click', event => {
          const isContain = this.el.nativeElement.contains(event.target);
          if (!isContain) {
            this.onClickOutside.emit();
          }
        });
      } else {
        this.handleClick();
      }
    }
  }
}
